package com.etrans.web.gps.business.platformTask.timer;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.etrans.web.gps.business.platformTask.domain.PlatformAnalyzes;
import com.etrans.web.gps.business.platformTask.domain.PlatformVO;
import com.etrans.web.gps.business.platformTask.service.SendMessageService;
import com.etrans.web.gps.business.system.service.SystemService;
import com.etrans.web.gps.common.MGTemplete;
import com.etrans.web.gps.common.SendMessageRecord;
import com.etrans.web.gps.util.Config;
import com.etrans.web.gps.util.DateUtil;
import com.etrans.web.gps.util.message.MailInfo;
import com.etrans.web.gps.util.message.MailSendUtil;

public class SendPlatMessage {
	
	private static final Logger logger = LoggerFactory.getLogger(SendPlatMessage.class);
	
	@Autowired
	private SendMessageService sendMessageService;
	
	@Autowired
	private SystemService system;
	
	@Autowired
	private Config config;
	
	/**
	 * 每周定时发送平台周考核通知(短信/邮件)
	 */
	public void sendMessageWeek() {
		try {
			// 获取当前日期的前一周
			Date  lastDay = DateUtil.getPreviousDayDate(7);
			int weekNum = DateUtil.getWeekNum(lastDay);
			String year = DateUtil.getDateToString(lastDay, "yyyy");
			Map<String,Object> lastWeek = DateUtil.getYearAndWeekByDate(Integer.valueOf(year),weekNum);
			Date lastMonday = DateUtil.getStringToDate(String.valueOf(lastWeek.get("Monday")));
			Date lastSunday = DateUtil.getStringToDate(String.valueOf(lastWeek.get("Sunday")));
			String week =  weekNum < 10 ? "0" + weekNum : ""+weekNum;
			String weekSE = "(" + DateUtil.getDateToString(lastMonday, "MM月dd日")  
							 + "-"+ DateUtil.getDateToString(lastSunday, "MM月dd日") + ")";
			String queryTime = DateUtil.getDateToString(lastMonday, "yyMMdd");
			long curr = System.currentTimeMillis();
			logger.info("发送平台周考核通知(短信/邮件)启动:第"+week+"周"+weekSE);
			// 查询所有的平台基本信息
			List<PlatformVO> platList = sendMessageService.queryAllPlatformList();
			// 查询所有的平台考核信息
			List<PlatformAnalyzes> platSwapList = sendMessageService.queryPlatAnalyzesWeek(queryTime);
			sendSMSProgram("week",year,week,weekSE,platList,platSwapList);
			sendEmailProgram("week",year,week,weekSE,platList,platSwapList,queryTime);
			logger.info("发送平台周考核通知(短信/邮件)完成:历时"+ String.valueOf(System.currentTimeMillis()-curr)+"秒");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("发送平台周考核通知(短信/邮件)启动失败!");
		}
	}
	
	/**
	 * 每月定时发送平台月考核通知(短信/邮件)
	 */
	public void sendMessageMonth() {
		try {
			//获取当前日期的前一月
			Date previousMonth = DateUtil.getPreviousMonthDate(1);
			String year = DateUtil.getDateToString(previousMonth, "yyyy");
			String month = DateUtil.getDateToString(previousMonth, "MM");
			String queryTime = DateUtil.getDateToString(previousMonth, "yyMM");
			long curr = System.currentTimeMillis();
			logger.info("发送平台月考核通知(短信/邮件)启动"+DateUtil.getDateToString(previousMonth, "yyyy年MM月"));
			// 查询所有的平台基本信息
			List<PlatformVO> platList = sendMessageService.queryAllPlatformList();
			// 查询所有的平台考核信息
			List<PlatformAnalyzes> platSwapList = sendMessageService.queryPlatAnalyzesMonth(queryTime);
			sendSMSProgram("month",year,month,"",platList,platSwapList);
			sendEmailProgram("month",year,month,"",platList,platSwapList,queryTime);
			logger.info("发送平台月考核通知(短信/邮件)完成:历时"+ String.valueOf(System.currentTimeMillis()-curr)+"秒");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("发送平台月考核通知(短信/邮件)启动失败!");
		}
	}
	
	/**
	 * 发送短信
	 * @param year			发送时间:年
	 * @param timeType		发送时间:月或周	
	 * @param detail		发送时间:时间段
	 * @param platList		所有平台列表
	 * @param platSwapList	查询到的平台信息
	 */
	private void sendSMSProgram(String timeType,String year,String time,String start_end,List<PlatformVO> platList,
			List<PlatformAnalyzes> platSwapList) {
		String detail = "";
		String areaName = system.getAreaName();
		if ("week".equals(timeType)) {
			detail = year + "年第" + time + "周" + start_end + areaName +"平台周考核信息：";
		}
		if ("month".equals(timeType)) {
			detail = year + "年" + time + "月" + areaName + "平台月考核信息：";
		}
		try {
			for (PlatformAnalyzes platformAna : platSwapList) {
				String gnss_centerid = platformAna.getGnss_centerid();
				for (PlatformVO platform : platList) {
					if (gnss_centerid.equals(String.valueOf(platform.getGnss_centerid()))) {
						//获取平台联系人信息，判断是否启动短息发送
						Integer enable_sms = platform.getEnable_sms();
						String contact_number = platform.getContact_number();
						if (enable_sms != null && enable_sms == 1 && contact_number != null) {
							//获取联系人和手机号
							String contacts = platform.getContacts();
							String email = platform.getEmail();
							String message = getSendSMSFormat(contacts,detail,platformAna);
							//短信发送
							//SMSUtil.mt(contact_number, message, "", "", "");
							System.out.println(message);
							//保存短信发送日志
							SendMessageRecord smr = new SendMessageRecord();
							smr.set_id(new ObjectId());
							smr.setEmail(email);
							smr.setPhone(contact_number);
							smr.setTips_time(new Date());
							smr.setTips_type(0);
							smr.setTarget_type(0);
							smr.setTarget_name(contacts);
							smr.setContent(message);
							MGTemplete.insertOne("egov", "tips_record", smr);
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("发送平台考核短信通知失败!");
		}
	}

	/**
	 * 发送邮件
	 * @param year			发送时间:年
	 * @param timeType		发送时间:月或周	
	 * @param detail		发送时间:时间段
	 * @param platList		所有平台列表
	 * @param platSwapList	查询到的平台信息
	 */
	private void sendEmailProgram(String timeType,String year,String time,String start_end,List<PlatformVO> platList,
			List<PlatformAnalyzes> platSwapList,String queryTime) {
		try {
			for (PlatformAnalyzes platformAna : platSwapList) {
				String gnss_centerid = platformAna.getGnss_centerid();
				for (PlatformVO platform : platList) {
					if (gnss_centerid.equals(String.valueOf(platform.getGnss_centerid()))) {
						//获取平台联系人信息，判断是否启动邮件发送
						Integer enable_email = platform.getEnable_email();
						String email = platform.getEmail();
						if (enable_email != null && enable_email == 1 && email != null) {
							//获取联系人和邮箱地址
							String contacts = platform.getContacts();
							String contact_number = platform.getContact_number();
							//邮件发送
							sendMail(contacts,email,timeType,year,time,start_end,platformAna,platSwapList);
							//保存邮件发送日志
							SendMessageRecord smr = new SendMessageRecord();
							smr.set_id(new ObjectId());
							smr.setPhone(contact_number);
							smr.setEmail(email);
							smr.setTips_time(new Date());
							smr.setTips_type(1);
							smr.setTarget_type(0);
							smr.setTarget_name(contacts);
							smr.setContent("mail/platform/queryPlatQCEmailRemind.html?platformId=" 
									+ platform.getPlatformId() + "&timeType=" + timeType + "&year=" + year 
									+ "&time=" + time + "&queryTime=" + queryTime);
							MGTemplete.insertOne("egov", "tips_record", smr);
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("发送平台考核邮件通知失败!");
		}
	}
	

	/**
	 * 提取信息，转化成邮件发送格式
	 * @param contacts 联系人
	 * @param timeType		发送时间:月或周	
	 * @param detail		发送时间:时间段
	 * @param platList		所有平台列表
	 * @param platSwapList	查询到的平台信息
	 * @return
	 */
	public void sendMail(String contacts,String email,String timeType,String year,String time,String start_end,
			PlatformAnalyzes platformAna, List<PlatformAnalyzes> platformAnaList) {
		System.out.println(email);
		String detail = "";
		String head = " ";
		if ("week".equals(timeType)) {
			detail = "周";
			head = "第";
		}
		if ("month".equals(timeType)) {
			detail = "月";
		}
		try {
	        String title = system.getAreaName() + "平台"+detail+"考核";
	        MailInfo info = new MailInfo();
	        info.setToAddress(email);
	        info.setSubject(title);
	        
	        //发送html格式
	        info.setFileName("emailMsgTemplate.html");
	        Map<String,Object> model = new HashMap<String,Object>();
	        //图片
	        model.put("pic", config.image_path);
	        //标题栏（数据填充）
	        model.put("contacts",contacts);
	        model.put("year",year);
	        model.put("time",time);
	        model.put("detail",detail);
	        model.put("head",head);
	        model.put("start_end",start_end);
	        model.put("order",platformAna.getRanking());
	        //统计栏
	        model.put("vehicleCount",platformAna.getVehicle_count());
	        model.put("vehicleNetCount",platformAna.getVehicle_access_count());
	        model.put("enterpriseCount", platformAna.getEnterprise_count());
	        DecimalFormat dft = new DecimalFormat("0.00");
	        double dealRate = platformAna.getAlarm_count() > 0 && platformAna.getAlarm_processed() > 0 ?
	        		100.00*platformAna.getAlarm_processed()/platformAna.getAlarm_count() : 0 ;
	        String dealRateStr = "0";
	        if (dealRate >= 1.00) {
	        	dealRateStr = "100";
			}else if (dealRate > 0) {
				dealRateStr = dft.format(dealRate);
			}
	        model.put("dealRate",dealRateStr);
	        //详细列表
	        String tableHead = " <tr><th>排名</th><th>得分</th><th>平台名称</th><th>平台连通率(%)</th><th>车辆总数(辆)</th>" + 
	        		"<th>入网车辆数(辆)</th><th>入网率(%)</th><th>上线率(%)</th><th>数据合格率(%)</th>" + 
	        		"<th>轨迹完整率(%)</th><th>卫星定位车辆飘移率(%)</th></tr>";
	        model.put("tableTitle","平台考核");
	        model.put("tableHead",tableHead);
	        StringBuffer platStr = new StringBuffer();
	        for (PlatformAnalyzes platAna : platformAnaList) {
	        	platStr.append("<tr>");
	        	//"排名:"
	        	platStr.append("<td>"+platAna.getRanking()+"</td>");
	        	//"得分:"
	        	platStr.append("<td>"+platAna.getScore()+"</td>");
	        	//平台名称
	        	platStr.append("<td>"+platAna.getPlatform_name()+"</td>");
	        	//"平台连通率:"
	        	platStr.append("<td>"+platAna.getOnline_rate()+"</td>");
				//"车辆总数:"
	        	platStr.append("<td>"+platAna.getVehicle_count()+"</td>");
				//"入网车辆数:"
	        	platStr.append("<td>"+platAna.getVehicle_access_count()+"</td>");
				//"车辆入网率:"
				int vehicle_count = platAna.getVehicle_count();
				platStr.append("<td>"+(vehicle_count <= 0 ? 0.00 : dft.format(platAna.getVehicle_access_rate()))+"</td>");
				//"车辆上线率:"
				platStr.append("<td>"+(vehicle_count <= 0 ? 0.00 : dft.format(platAna.getVehicle_online_rate()))+"</td>");
				//"数据合格率:"
				int trackNum = platAna.getTrack_normal()+platAna.getException_track_count();
				platStr.append("<td>"+(trackNum <= 0 ? 0.00 :dft.format(100.00*platAna.getTrack_normal()/trackNum))+"</td>");
				//"轨迹完整率:"
				platStr.append("<td>"+dft.format(platAna.getTrack_complete_rate())+"</td>");
				//"定位漂移车辆比率:"
				int sum = platAna.getLocation_exception_count()+platAna.getSpeed_160_count()+platAna.getGpstime_exception_count()+platAna.getHead_exception_count();
				double avg = sum<=0 ? 0 : (100.00 *platAna.getLocation_exception_count()) / sum;
				double result = platAna.getVehicle_online_count() <= 0 ? 0 : (avg*platAna.getException_vehicle_count())/platAna.getVehicle_online_count();
				platStr.append("<td>"+dft.format(result)+"</td>");
				platStr.append("</tr>");
	        }
	        model.put("resultList",platStr.toString());
            MailSendUtil.sendHtmlMail(info,model);
        } catch (Exception e) {
        	logger.error("邮件发送失败！");
            e.printStackTrace();
        }
	}
	
	/**
	 * 提取信息，转化成短信发送格式
	 * @param contacts 联系人
	 * @param year 
	 * @param msgTime 信息的统计时间
	 * @param detail 
	 * @param platformAna 
	 * @return
	 */
	public String getSendSMSFormat(String contacts,String detail, PlatformAnalyzes platformAna) {
		DecimalFormat dft = new DecimalFormat("0.00");
		StringBuffer stb = new StringBuffer();
		stb.append("尊敬的"+contacts+"先生，您好！"+detail);
		stb.append("平台名称:"+platformAna.getPlatform_name()+"；");
		stb.append("得分:"+platformAna.getScore()+"；");
		stb.append("排名:"+platformAna.getRanking()+"；");
		stb.append("车辆总数:"+platformAna.getVehicle_count()+"辆；");
		stb.append("入网车辆数:"+platformAna.getVehicle_access_count()+"辆；");
		stb.append("平台连通率:"+dft.format(platformAna.getOnline_rate())+"%；");
		
		int vehicle_count = platformAna.getVehicle_count();
		int vehicle_access_count = platformAna.getVehicle_access_count();
		stb.append("车辆入网率:"+(vehicle_count <= 0 ? 0 : dft.format(100.00*vehicle_access_count/vehicle_count))+"%; ");
		stb.append("车辆上线率:"+(vehicle_access_count <= 0 ? 0 : dft.format(100.00*platformAna.getVehicle_online_count()/vehicle_access_count))+"%; ");
		
		int trackNum = platformAna.getTrack_normal()+platformAna.getException_track_count();
		stb.append("数据合格率:"+(trackNum <= 0 ? 0 :dft.format(100.0*platformAna.getTrack_normal()/trackNum))+"%；");
		stb.append("轨迹完整率:"+dft.format(platformAna.getTrack_complete_rate())+"%；");
		
		int sum = platformAna.getLocation_exception_count()+platformAna.getSpeed_160_count()+platformAna.getGpstime_exception_count()+platformAna.getHead_exception_count();
		double avg = sum<=0 ? 0 : (100.00 *platformAna.getLocation_exception_count()) / sum;
		double result = platformAna.getVehicle_online_count() <= 0 ? 0 : (avg*platformAna.getException_vehicle_count())/platformAna.getVehicle_online_count();
		stb.append("定位漂移车辆比率:"+dft.format(result)+"% 。");
		return stb.toString();
	}
}
